<?php

namespace app\proxy\controller;

use app\api\model\WithdrawStyle;
use think\Cache;
use think\Db;
use think\Image;
use think\Session;
use PHPQRCode\QRcode;

class Index extends Common
{
    public $member = null;

    public function __construct()
    {
        parent::__construct();

        $uid = Session::get('proxy', 'ffxiangAd');
        $member = _user($uid['id']);
        $this->member = $member;
    }

    public function index()
    {
        $member = Session::get('proxy', 'ffxiangAd');

        $url = url('/', '', '', true) . '?yq=' . $member['id'];

        $this->assign('qrcode', $member['qrcode']);
        $this->assign('url', $url);
        $this->assign('uid', $this->member);
        return $this->fetch();
    }

    public function main()
    {
        $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

        $data = [];
        $data['topup_day'] = Db::name("topup")->where(['fk_userid' => ['in', $ids], 'state' => 1])->whereTime('addtime', 'd')->sum("price");
        $data['topup_month'] = Db::name("topup")->where(['fk_userid' => ['in', $ids], 'state' => 1])->whereTime('addtime', 'm')->sum("price");

        $data['reg_day'] = Db::name('user')->where(['yqr' => $this->member['yqm']])->whereTime('register_datetime', 'd')->count();
        $data['reg_month'] = Db::name('user')->where(['yqr' => $this->member['yqm']])->whereTime('register_datetime', 'm')->count();

        $data['shouyi_day'] = Db::name('yaoqing_records')->where(['uid' => $this->member['id'], 'content' => ['like', '%收益%']])->whereTime('time', 'd')->sum('money');
        $data['shouyi_month'] = Db::name('yaoqing_records')->where(['uid' => $this->member['id'], 'content' => ['like', '%收益%']])->whereTime('time', 'm')->sum('money');

        $this->assign('ids', $ids);
        $this->assign('data', $data);

        return $this->fetch();
    }

    public function member()
    {
        $uid = $this->member['id'];
        $this->assign('user', $uid);
        $this->assign('name', $this->member);

        if (request()->isAjax()) {
            $post = input('post.');
            if ($post) {
                $post;
                if ($post['type'] == '1') {
                    if ($post['repassword'] == $post['password']) {
                        $password = db('member')->where('id', $uid)->value('password');
                        if ($password == md5($post['oldpassword'])) {
                            $data['nickname'] = $post['nickname'];
                            $data['password'] = md5($post['password']);
                        } else {
                            $data = ['ret' => '当前密码错误'];
                        }
                    } else {
                        $data = ['ret' => '两次输入密码不一致，请重新输入'];
                    }
                } else {
                    $data['nickname'] = $post['nickname'];
                }
                $res = db('member')->where('id', $uid)->update($data);
                if ($res === false) {
                    $data = ['err' => '保存失败'];
                } else {
                    $data = ['ret' => '保存成功'];
                }

            } else {
                $data = ['err' => '提交参数错误'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    //清空缓存
    public function cache_del()
    {
        Cache::clear();
        return ['ret' => '清空成功'];
    }

    //上传图片
    public function upload()
    {
        if (request()->file('image')) {

            $switch = getenv('APP_OSS');

            if (!$switch) { //默认存本地服务器
                $file = request()->file('image');
                //$image = Image::open($file);
                $filePath = $file->getRealPath();
                if (!$filePath) {
                    exit(json_encode(['err' => '非法操作']));
                }

                if ($file) {
                    $info = $file->move(ROOT_PATH . 'disk');

                    if ($info) {
                        $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());

                        $thumb_ = explode('.', $info->getFilename());
                        //$image->thumb(800, 800)->save(ROOT_PATH . 'disk' . DS . date('Ymd') . DS . $thumb_[0] . '_thumb.' . $thumb_[1]);
                        //$info = $file->move(ROOT_PATH . 'disk' . DS . 'uploads');

                        //$new = '/disk/' . $arr[0] . '/' . $arr[1];
                        $new = '/disk/' . $info->getSaveName();

                        return $new;
                    } else {
                        return json(['err' => $file->getError()]);
                    }
                }
            } else {
                $file = $_FILES['image'];

                if ($file) {
                    $image = \think\Image::open($file['tmp_name']);

                    $name = $file['name'];
                    $format = strrchr($name, '.');

                    $new = sha1(date('YmdHis', time()) . uniqid()) . $format;

                    //$image->thumb(1000, 1000)->save(ROOT_PATH . 'disk' . DS . $new);
                    $image->save(ROOT_PATH . 'disk' . DS . $new);

                    /*判断图片格式*/
                    /*$allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
                    if (!in_array($format, $allow_type)) {
                        exit(json_encode(['code' => 400, 'msg' => '文件格式不在允许范围内哦']));
                    }*/

                    $dir = 'disk/uploads/image/' . date("Ymd") . '/';
                    $fileName = $dir . $new;
                    $localFile = str_replace('/index.php', '', $_SERVER['SCRIPT_FILENAME']) . '/disk/' . $new;

                    $accessKeyId = getenv('OSS_KEYID');
                    $accessKeySecret = getenv('OSS_KEYSECRET');
                    $endpoint = getenv('OSS_ENDPOINT');
                    $bucket = getenv('OSS_BUCKET');

                    try {
                        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                        $result = $ossClient->uploadFile($bucket, $fileName, $localFile);

                        $thumb_ = explode('.', $new);
                        $thumb1 = $dir . $thumb_[0] . '_thumb.' . $thumb_[1];

                        $result = $ossClient->uploadFile($bucket, $thumb1, $localFile);

                    } catch (OssException $e) {
                        return json(['code' => 400, 'msg' => $e->getMessage()]);
                    }

                    unlink($localFile);

                    return '/' . $fileName;
                }
            }

        } else {
            return $this->fetch();
        }
    }

    //上传图片
    public function uploadxiao()
    {
        if (request()->file('image')) {
            $file = request()->file('image');
            $image = Image::open($file);
            $filePath = $file->getRealPath();
            if (!$filePath) {
                exit(json_encode(['err' => '非法操作']));
            }

            if ($file) {
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());

                    $new = 'public/uploads/' . $arr[0] . '/' . $arr[1];

                    $image->thumb(665, 665)->save($new);
                    return '/' . $new;
                } else {
                    dump($file->getError());
                }
            }
        } else {
            return $this->fetch();
        }
    }

    //图片集
    public function uploads()
    {
        if (request()->isPost()) {

            $file = request()->file('file');
            $image = Image::open($file);

            $filePath = $file->getRealPath();
            if (!$filePath) {
                exit(json_encode(['err' => '非法操作']));
            }
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //后缀
            $geshi = ['jpg', 'mp4', 'png', 'gif', 'jpeg', 'JPEG', 'JPG', 'GIF', 'PNG'];
            if (!in_array($ext, $geshi)) {
                exit(json_encode(['err' => '图片格式不对，请换张图片吧']));
            }

            if ($file) {
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'memberad');

                $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());

                $new = 'public/uploads/memberad/' . $arr[0] . '/' . $arr[1];

                $image->thumb(2000, 2000)->save($new);
                if ($info) {
                    $data = ['img' => '/' . $new, 'imgurl' => '/' . $new, 'text' => ''];
                    return json_encode($data);
                } else {
                    dump($file->getError());
                }
            }
        }
    }

    //退出登陆
    public function out()
    {
        session(null, 'ffxiangAd');
        $this->redirect("login/index");
    }

    // 第三方登录配置
    public function sdk()
    {
        return $this->fetch();
    }

    public function videoUploads()
    {
        if (request()->file('file')) {

            $file = request()->file('file');

            if ($file) {
                $info = $file->validate(['ext' => 'mp4'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'memberad');

                if ($info) {
                    $arr = explode(DIRECTORY_SEPARATOR, $info->getSaveName());

                    $new = '/public/uploads/memberad/' . $arr[0] . '/' . $arr[1];
                    echo json_encode(['ret' => $new]);
                } else {
                    echo json_encode(['err' => $file->getError()]);
                }
            }
        } else {
            return $this->fetch('uploadvideo');
        }
    }

    public function lists()
    {
        $map = [];
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['register_datetime'] = ['between', [date('Y-m-d H:i:s', strtotime($start)), date('Y-m-d H:i:s', strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['register_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime($start))];
        } else if (!$start && $end) {
            $map['register_datetime'] = ['lt', date('Y-m-d H:i:s', strtotime($start) + 86400)];
        }

        $map['yqr'] = $this->member['yqm'];

        $data = Db::name('user')->order('id desc')->where($map)->paginate('', false, ['query' => request()->param()]);

        $sum = Db::name('user')->where($map)->count();

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('sum', $sum);

        return $this->fetch();
    }

    public function addlists()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $post['fencheng_user'] = $post['fencheng_user'] / 100;

            if ($id) {
                $db = Db::name('user')->where('id', $id)->update($post);
                if ($db === false) {
                    $data = ['err' => '修改失败'];
                } else {
                    $data = ['ret' => '修改成功'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 添加会员
    public function add()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$post['phone']) {
                return ['err' => '手机不能为空'];
            }
            if (!$post['name']) {
                return ['err' => '昵称不能为空'];
            }

            if (!$id) {   // 添加数据
                if (input('phone')) {
                    $userdb = Db::name('user')->where('phone', $post['phone'])->value('user_id');
                    if ($userdb) {
                        return ['err' => '手机已存在'];
                    }
                }

                if (!$post['password']) {
                    return ['err' => '请填写密码'];
                }
                $post['addtime'] = date('Y-m-d H:i:s'); // 添加时间

                $post['yaoqing'] = $this->member['user_id'];

                $db = Db::name('user')->insertGetId($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                $member = Db::name('user')->where('user_id', $id)->value('password');

                if (input('phone')) {
                    $userdb = Db::name('user')->where('phone', $post['phone'])->value('user_id');
                    if ($userdb && $userdb != $id) {
                        return ['err' => '手机已存在'];
                    }
                }
                if (!$post['password']) {
                    $post['password'] = $member;
                }

                $db = Db::name('user')->where('user_id', $id)->update($post);
                if ($db === false) {
                    $data = ['err' => '修改失败'];
                } else {
                    $data = ['ret' => '修改成功'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('user')->where('user_id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    //删除会员
    public function del()
    {
        if (request()->isAjax()) {

            $id = input('id');

            if ($id) {
                Db::name('user')->where('user_id', $id)->delete();
                $data = ['ret' => '删除成功'];
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    // 开通vip记录
    public function viporder()
    {
        $id = $this->member['id'];

        $search_name = input('param.search_name');
        $search_typeid = input('param.search_typeid');

        $map = [];
        if ($search_typeid && $search_name) {
            $map['t2.' . $search_typeid] = ['like', '%' . $search_name . '%'];
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['t1.time'] = ['between', [strtotime($start), (strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['t1.time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.time'] = ['lt', (strtotime($start) + 86400)];
        }

        $date = input('date');

        $whereTime = '';
        if ($date) {
            switch ($date) {
                case 1:
                    $whereTime = 'd';
                    break;
                case 2:
                    $whereTime = 'yesterday';
                    break;
                case 3:
                    $whereTime = 'month';
                    break;
                case 4:
                    $whereTime = 'last month';
                    break;
            }
        }

        $types = input('types/d') ?: 0;

        $map['t1.types'] = $types;


        $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

        $map['t1.user_id'] = ['in', $ids];

        if ($whereTime) {
            $data = Db::name('volley_desc t1')->field('t1.*,t2.name, t2.phone')->join('user t2', 't2.id = t1.user_id')->where($map)->whereTime('time', $whereTime)->order('t1.id desc')->paginate('', false, ['query' => request()->param()]);;
            $money = Db::name('volley_desc t1')->join('user t2', 't2.id = t1.user_id')->where($map)->whereTime('time', $whereTime)->sum('t1.price');
        } else {
            $data = Db::name('volley_desc t1')->field('t1.*,t2.name, t2.phone')->join('user t2', 't2.id = t1.user_id')->where($map)->order('t1.id desc')->paginate('', false, ['query' => request()->param()]);
            $money = Db::name('volley_desc t1')->join('user t2', 't2.id = t1.user_id')->where($map)->sum('t1.price');
        }

        $page = $data->render();

        $this->assign('types', $types);
        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('date', $date);
        $this->assign('money', $money);
        $this->assign('shouyi', $this->member['shouyi']);
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    // ====================================================

    // 提现记录
    public function withdraw()
    {
        $map = [];

        $id = $this->member['id'];

        $next = input('next');

        if ($next) {
            $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

            $map['t1.userid'] = $ids ? ['in', $ids] : 0;
        } else {
            $id = $this->member['id'];
            $map['t1.userid'] = $id;
        }

        $search_name = input('param.search_name');
        $search_typeid = input('param.search_typeid');


        if ($search_typeid && $search_name) {
            $map['t2.' . $search_typeid] = ['like', '%' . $search_name . '%'];
        }

        $paymethod = input('paymethod');

        if ($paymethod !== null) {
            $map['t1.paymethod'] = $paymethod;
        }

        $state = input('state');

        if ($state !== null) {
            $map['t1.state'] = $state;
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['t1.create_time'] = ['between', [strtotime($start), (strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.create_time'] = ['lt', (strtotime($start) + 86400)];
        }

        $data = Db::name('withdraw t1')
            ->field('t1.*,t2.name,t2.zhifuname,t2.zhifucount,t2.wxname,t2.wxcount')
            ->join('user t2', 't2.id = t1.userid')->where($map)->order('t1.id desc')->paginate('', false, ['query' => request()->param()]);;
        $page = $data->render();

        $month = db('withdraw')->alias('t1')->join('user t2', 't2.id = t1.userid')->where($map)->whereTime('create_time', 'm')->sum('t1.money');
        $sum = db('withdraw')->alias('t1')->join('user t2', 't2.id = t1.userid')->where($map)->sum('t1.money');

        $this->assign('month', $month);
        $this->assign('sum', $sum);
        $this->assign('paymethod', $paymethod);
        $this->assign('state', $state);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('data', $data);
        $this->assign('page', $page);
        $this->assign('next', $next);

        return $this->fetch();
    }

    // 申请提现
    public function addwithdraw1()
    {

        $id = $this->member['id'];

        if (request()->isAjax()) {

            $post = input('post.');

            /*if (!isset($post['money']) || $post['money'] <= 0) {
                return ['err' => '金额不正确'];
            }*/

            //$post['money'] *= 10;

            //$time = date("Y-m-d H:i:s", time() + 259200);

            $style = Db::name('withdraw_style')->find($post['style']);

            if (!$style) {
                return ['err' => '选择有误'];
            }

            if (($this->member['score']) < $style['price']) {
                return ['err' => '账户余额不足'];
            }

            /*if (($this->member['score']) < 1) {
                return ['err' => '提现金额不能低于1'];
            }*/

            $user = Db::name('user')->where(['id' => $id])->find();

            if (!$post['method']) {
                if (!$user['wxname'] || !$user['wxcount']) {
                    return ['err' => '先绑定微信'];
                }

                $txaccount = $user['wxcount'];
                $txname = $user['wxname'];
            } else if ($post['method'] == 1) {
                if (!$user['zhifuname'] || !$user['zhifucount']) {
                    return ['err' => '先绑定支付宝'];
                }

                $txaccount = $user['zhifucount'];
                $txname = $user['zhifuname'];
            }

            $rate = Db::name('config_system')->where(['title' => 'rate'])->value('content');

            $insertArr = array(
                "userid" => $id,
                "paymethod" => $post['method'],
                "money" => $style['money'],
                //'price' => $post['money'] / $rate,
                //'price' => $post['money'] * 10,
                'price' => $style['price'] * 1,
                "create_time" => time(),
                "update_time" => time(),
                'txaccount' => $txaccount,
                'txname' => $txname,
                'data' => json_encode(['name' => $txname, 'account' => $txaccount])
            );
            $db = Db::name('withdraw')->insert($insertArr);
            //$db = Db::name('user')->where(['id' => $id])->setDec('score', $post['money'] * 10);
            $db = Db::name('user')->where(['id' => $id])->setDec('score', $style['price'] * 1);

            if ($db) {
                $data = ['ret' => '申请提交成功'];
            } else {
                $data = ['err' => '申请提交失败'];
            }
        } else {
            $result = Db::name('withdraw')->where(['userid' => $this->member['id'], 'state' => ['neq', 2]])->value('id');

            $first = $result ? 0 : 1;

            $where = $first ? ['id' => ['gt', 0]] : ['is_first' => 0];


            $withdrawStyle = WithdrawStyle::all(function($query) use ($where) {
                $query->field('is_first, sort, create_time', true)->where($where)->order('sort desc');
            });

            foreach ($withdrawStyle as $key => $item) {
                $withdrawStyle[$key]['price'] =  sprintf("%.0f", $item['price']);
                $withdrawStyle[$key]['money'] =  sprintf("%.0f", $item['money']);
            }

            $this->assign('withdrawStyle', $withdrawStyle);

            $data = $this->fetch();
        }
        return $data;
    }

    public function addwithdraw()
    {

        $id = $this->member['id'];

        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['money']) || $post['money'] <= 0) {
                return ['err' => '金额不正确'];
            }

            $money = $post['money'] * 10;

            if (($this->member['score']) < $money) {
                return ['err' => '账户余额不足'];
            }

            if ($post['money'] < 1) {
                return ['err' => '提现金额不能低于1'];
            }

            $user = Db::name('user')->where(['id' => $id])->find();

            if (!$post['method']) {
                if (!$user['wxname'] || !$user['wxcount']) {
                    return ['err' => '先绑定微信'];
                }

                $txaccount = $user['wxcount'];
                $txname = $user['wxname'];
            } else if ($post['method'] == 1) {
                if (!$user['zhifuname'] || !$user['zhifucount']) {
                    return ['err' => '先绑定支付宝'];
                }

                $txaccount = $user['zhifucount'];
                $txname = $user['zhifuname'];
            }

            $rate = Db::name('config_system')->where(['title' => 'rate'])->value('content');

            $insertArr = array(
                "userid" => $id,
                "paymethod" => $post['method'],
                "money" => $post['money'],
                //'price' => $post['money'] / $rate,
                'price' => $money,
                "create_time" => time(),
                "update_time" => time(),
                'txaccount' => $txaccount,
                'txname' => $txname,
                'data' => json_encode(['name' => $txname, 'account' => $txaccount])
            );
            $db = Db::name('withdraw')->insert($insertArr);
            $db = Db::name('user')->where(['id' => $id])->setDec('score', $money);

            if ($db) {
                $data = ['ret' => '申请提交成功'];
            } else {
                $data = ['err' => '申请提交失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function bdzhifubao()
    {

        $id = $this->member['id'];

        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['zhifucount']) || !$post['zhifucount']) {
                return ['err' => '先填写支付宝账号'];
            }

            if (!isset($post['zhifuname']) || !$post['zhifuname']) {
                return ['err' => '先填写支付宝名'];
            }

            $db = Db::name('user')->where(['id' => $id])->update(['zhifucount' => $post['zhifucount'], 'zhifuname' => $post['zhifuname']]);

            if ($db !== false) {
                $data = ['ret' => '绑定成功'];
            } else {
                $data = ['err' => '绑定失败'];
            }
        } else {
            $name = Db::name('user')->where('id', $id)->find();
            $this->assign('name', $name);
            $data = $this->fetch();
        }
        return $data;
    }

    public function bdwechat()
    {

        $id = $this->member['id'];

        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['wxcount']) || !$post['wxcount']) {
                return ['err' => '先填写微信账号'];
            }

            if (!isset($post['wxname']) || !$post['wxname']) {
                return ['err' => '先填写微信名'];
            }

            $db = Db::name('user')->where(['id' => $id])->update(['wxcount' => $post['wxcount'], 'wxname' => $post['wxname']]);

            if ($db) {
                $data = ['ret' => '绑定成功'];
            } else {
                $data = ['err' => '绑定失败'];
            }
        } else {
            $name = Db::name('user')->where('id', $id)->find();
            $this->assign('name', $name);
            $data = $this->fetch();
        }
        return $data;
    }

    // 开通vip记录
    public function vipdingdan()
    {
        $id = $this->member['id'];

        $search_name = input('param.search_name');
        $search_typeid = input('param.search_typeid');

        $map = [];
        if ($search_typeid && $search_name) {
            $map['t2.' . $search_typeid] = ['like', '%' . $search_name . '%'];
        }

        $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

        $map['t1.user_id'] = ['in', $ids];

        $map['t1.type'] = 1;
        $map['t1.desc'] = ['not like', '管理%'];

        $data = Db::name('vip_order t1')->field('t1.*,t2.name, t2.phone')->join('user t2', 't2.id = t1.user_id')->where($map)->order('t1.id desc')->paginate('', false, ['query' => request()->param()]);;
        $page = $data->render();

        $this->assign('shouyi', $this->member['shouyi']);
        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    // 下级充值记录
    public function topup()
    {
        $id = $this->member['id'];

        $search_name = input('param.search_name');
        $search_typeid = input('param.search_typeid');

        $map = [];
        if ($search_typeid && $search_name) {
            $map['t2.' . $search_typeid] = ['like', '%' . $search_name . '%'];
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['t1.addtime'] = ['between', [date('Y-m-d H:i:s', strtotime($start)), date('Y-m-d H:i:s', strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['t1.addtime'] = ['egt', date('Y-m-d H:i:s', strtotime($start))];
        } else if (!$start && $end) {
            $map['t1.addtime'] = ['lt', date('Y-m-d H:i:s', strtotime($start) + 86400)];
        }

        $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

        $map['t1.fk_userid'] = ['in', $ids];
        $map['t1.state'] = 1;

        $data = Db::name('topup t1')
            ->field('t1.*,t2.name, t2.phone')
            ->join('user t2', 't2.id = t1.fk_userid')
            ->where($map)
            ->order('t1.id desc')->paginate('', false, ['query' => request()->param()]);

        $sum = Db::name('topup t1')->where($map)->sum('price');

        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('sum', $sum);

        return $this->fetch();
    }

    // 下级付费订单
    public function order()
    {
        $id = $this->member['id'];

        $search_name = input('param.search_name');
        $search_typeid = input('param.search_typeid');

        $map = [];
        if ($search_typeid && $search_name) {
            $map['t2.' . $search_typeid] = ['like', '%' . $search_name . '%'];
        }

        $types = input('types');
        if ($types) {
            $where['t1.types'] = $types;
        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['t1.update_time'] = ['between', [strtotime($start), (strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['t1.update_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['t1.update_time'] = ['lt', (strtotime($start) + 86400)];
        }

        $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

        $map['t1.user_id'] = ['in', $ids];
        $map['t1.status'] = 1;
        $map['t1.pays'] = ['neq', 1];

        $data = Db::name('order_common t1')
            ->field('t1.*,t2.name, t2.phone')
            ->join('user t2', 't2.id = t1.user_id')
            ->where($map)
            ->order('t1.id desc')->paginate('', false, ['query' => request()->param()]);

        $sum = Db::name('order_common t1')->where($map)->sum('money');

        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        $this->assign('start', $start);
        $this->assign('end', $end);

        $this->assign('types', $types);

        $this->assign('sum', $sum);

        return $this->fetch();
    }

    // 收益记录
    public function shouyirecords()
    {
        $next = input('next');

        if ($next) {
            $ids = Db::name('user')->where(['yqr' => $this->member['yqm']])->column('id');

            $map['uid'] = $ids ? ['in', $ids] : 0;
        } else {
            $id = $this->member['id'];
            $map['uid'] = $id;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($next) {
                $map['uid'] = ['like', '%' . $search_name . '%'];
            } else {
                $map[$search_type] = ['like', '%' . $search_name . '%'];
            }

        }

        $start = input('start');
        $end = input('end');
        if ($start && $end) {
            $map['time'] = ['between', [strtotime($start), (strtotime($end) + 86400)]];
        } else if ($start && !$end) {
            $map['time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $map['time'] = ['lt', (strtotime($start) + 86400)];
        }

        $date = input('date');

        $whereTime = '';
        if ($date) {
            switch ($date) {
                case 1:
                    $whereTime = 'd';
                    break;
                case 2:
                    $whereTime = 'yesterday';
                    break;
                case 3:
                    $whereTime = 'month';
                    break;
                case 4:
                    $whereTime = 'last month';
                    break;
            }
        }

        //$map['content'] = ['like', '%收益%'];
        $map['type'] = 1;
        $map['data'] = 0;
        $map['money'] = ['gt', 0];

        if ($whereTime) {
            $data = Db::name('yaoqing_records')->where($map)->whereTime('time', $whereTime)->order('id desc')->paginate('', false, ['query' => request()->param()]);

            $shouyi = Db::name('yaoqing_records')->where($map)->whereTime('time', $whereTime)->sum('money');
        } else {
            $data = Db::name('yaoqing_records')->where($map)->order('id desc')->paginate('', false, ['query' => request()->param()]);
            $shouyi = Db::name('yaoqing_records')->where($map)->sum('money');
        }

        $page = $data->render();

        $this->assign('shouyi', $shouyi);
        $this->assign('data', $data);
        $this->assign('page', $page);

        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('date', $date);
        $this->assign('next', $next);

        return $this->fetch();
    }

    public function next()
    {
        $map = [];
        $search_name = input('param.name');
        $search_type = input('param.type');
        if ($search_name && $search_type) {
            $map[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $map['admin'] = $this->member['id'];

        $data = Db::name('user')->order('id desc')->where($map)->paginate('', false, ['query' => request()->param()]);

        $sum = Db::name('user')->where($map)->count();

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('sum', $sum);

        return $this->fetch();
    }

    public function addNext()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (isset($post['fencheng_vip'])) {
                $post['fencheng_vip'] = $post['fencheng_vip'] / 100;
            }

            if (isset($post['fencheng_topup'])) {
                $post['fencheng_topup'] = $post['fencheng_topup'] / 100;
            }

            if (isset($post['fencheng_chat'])) {
                $post['fencheng_chat'] = $post['fencheng_chat'] / 100;
            }

            if (isset($post['fencheng_prev'])) {
                $post['fencheng_prev'] = $post['fencheng_prev'] / 100;
            }

            if (!$id) {
                if (!$post['name']) {
                    return ['err' => '请填写账号'];
                }
                if (!$post['password']) {
                    return ['err' => '请填写密码'];
                }

                $user = Db::name('user')->where(['name' => $post['name'], 'proxy' => 1])->find();
                if ($user) {
                    return ['err' => '账号已存在'];
                }

                //生成唯一邀请码
                for ($i = 2; $i > 1; $i++) {
                    $code = code();

                    $test = Db::name('user')->where('yqm', $code)->select();
                    if (!$test) {
                        $i = 0;
                    }
                }

                $post['yqm'] = $code;
                $post['proxy'] = 1;
                $post['admin'] = $this->member['id'];

                $result = Db::name('user')->insert($post);

                $data = $result ? ['ret' => '添加成功'] : ['err' => '添加失败'];
            } else {

                if (isset($post['password']) && !$post['password']) {
                    unset($post['password']);
                }

                if ($post['name']) {
                    $user = Db::name('user')->where(['id' => ['neq', $id], 'name' => $post['name'], 'proxy' => 1])->find();
                    if ($user) {
                        return ['err' => '账号已存在'];
                    }
                }

                $db = Db::name('user')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('user')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }

    public function download()
    {
        $id = $this->member['id'];

        $data = Db::name('proxy_download')->where(['user_id' => $this->member['id']])->order('id desc')->paginate('', false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function adddown()
    {
        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['url']) || !$post['url']) {
                return ['err' => '请先上传文件'];
            }
            $post['user_id'] = $this->member['id'];
            $post['image'] = $this->createTempQrcode(changeUrl($post['url']));
            $post['create_time'] = time();

            $db = Db::name('proxy_download')->insert($post);

            if ($db) {
                $data = ['ret' => '提交成功'];
            } else {
                $data = ['err' => '提交失败'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function downdel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('proxy_download')->where(['id' => $id, 'user_id' => $this->member['id']])->delete();
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    /**
     * 生成临时二维码图片
     * 这里返回的是base64进制图片
     * 一般用于微信扫码支付二维码生成场景
     *
     * @param string $data 二维码内容
     *         示例数据：http://www.tf4.cn或weixin://wxpay/bizpayurl?pr=0tELnh9
     *
     * @return
     */
    public function createTempQrcode($data)
    {
        $object = new QRcode();
        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 5;            //生成图片大小

        //打开缓冲区
        ob_start();
        //生成二维码图片
        $returnData = $object->png($data,false,$errorCorrectionLevel, $matrixPointSize, 2);
        //这里就是把生成的图片流从缓冲区保存到内存对象上，使用base64_encode变成编码字符串，通过json返回给页面。
        $imageString = base64_encode(ob_get_contents());
        //关闭缓冲区
        ob_end_clean();
        $base64 = "data:image/png;base64,".$imageString;

        $result['errcode'] = 0;
        $result['errmsg'] = 'ok';
        $result['data'] = $base64;

        return $base64;
    }
}
